<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { addDeptServerApi } from "@/api/clusters/deptServer";
import { useLogic } from "@/views/system/user/logic/logic";
import { getClusterTypes } from "@/utils/appCommon/appCommonOptions/clusters";
import { getClusterServerKeysApi } from "@/api/clusters/clusterServer";

const { t } = useI18n();

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const {deptTreeList,getDeptTree}  = useLogic()
const clusterTypeOptions = ref([])
onMounted(async () => {
  clusterTypeOptions.value = await getClusterTypes()
  await getDeptTree()
})

// 添加本地对话框状态
const dialogVisible = ref(props.visible);

// 监听prop变化同步到本地状态
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  },
  { immediate: true }
);

// 监听本地状态变化通知父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 定义emits
const emit = defineEmits(['update:visible', 'success']);

const formData = ref({
  deptId: '',
  serverKey: '',
  type: '',
  remark: ''
});

const submitForm = async () => {
  try {
    const response = await addDeptServerApi({
      deptId: formData.value.deptId,
      serverKey: formData.value.serverKey,
      type: formData.value.type,
      remark: formData.value.remark
    });

    if (response.code === 0) {
      ElMessage.success(t('clusters.deptServerPage.addSuccess'));
      emit('update:visible', false);
      emit('success');
      resetForm();
    } else {
      ElMessage.error(response.msg || t('clusters.deptServerPage.addFail'));
    }
  } catch (error) {
    ElMessage.error(t('clusters.deptServerPage.addFail'));
  }
};

const resetForm = () => {
  formData.value = {
    deptId: '',
    serverKey: '',
    type: '',
    remark: ''
  };
};

const serverKeyOptions = ref<Array<{label: string, val: string}>>([]);

// 监听类型变化
watch(() => formData.value.type, async (newType) => {
  if (newType) {
    try {
      const response = await getClusterServerKeysApi(newType);
      if (response.code === 0) {
        serverKeyOptions.value = response.data?.options || [];
      } else {
        ElMessage.error(response.message || '获取服务器标识失败');
      }
    } catch (error) {
      ElMessage.error(t('clusters.deptServerPage.getServerKeyFail'));
    }
  } else {
    serverKeyOptions.value = [];
  }
}, { immediate: true });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('clusters.deptServerPage.addTitle')"
    :draggable="true"
    @close="emit('update:visible', false)"
  >
    <el-form :model="formData" label-width="100px">
      <el-form-item :label="t('clusters.deptServerPage.deptName')" prop="deptId" required>
        <el-cascader
          v-model="formData.deptId"
          class="w-full"
          :options="deptTreeList"
          :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
          clearable
          filterable
          :placeholder="t('clusters.deptServerPage.selectDeptPlaceholder')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>

      <el-form-item :label="t('clusters.deptServerPage.type')" prop="type">
        <el-select v-model="formData.type" :placeholder="t('clusters.deptServerPage.typePlaceholder')">
          <el-option v-for="opt in clusterTypeOptions" :key="opt.val" :label="opt.label" :value="opt.val" />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('clusters.deptServerPage.serverKey')" prop="serverKey" required>
        <el-select
          v-model="formData.serverKey"
          :placeholder="t('clusters.deptServerPage.selectServerKeyPlaceholder')"
          clearable
          filterable
        >
          <el-option
            v-for="opt in serverKeyOptions"
            :key="opt.val"
            :label="opt.label"
            :value="opt.val"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('clusters.deptServerPage.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :placeholder="t('clusters.deptServerPage.remarkPlaceholder')"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="resetForm">{{ t('buttons.reset') }}</el-button>
      <el-button type="primary" @click="submitForm">{{ t('buttons.submit') }}</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
